package delayQueue

import java.util.concurrent.TimeUnit

import org.redisson.api.{RBlockingQueue, RDelayedQueue, RedissonClient}

/**
  * 延时job服务
  **/
object DelayJobService {

  def submitJob(client: RedissonClient, delayQueueName: String, delayJob: DelayJob, delay: Long, timeUnit: TimeUnit): Unit = {
    val blockingQueue: RBlockingQueue[DelayJob] = client.getBlockingQueue(delayQueueName)
    val delayedQueue: RDelayedQueue[DelayJob] = client.getDelayedQueue(blockingQueue)

    delayedQueue.offer(delayJob, delay, timeUnit)
    delayedQueue.destroy()
  }

  def cancelJob(client: RedissonClient, delayQueueName: String, delayJob: DelayJob): Boolean = {
    val blockingQueue: RBlockingQueue[DelayJob] = client.getBlockingQueue(delayQueueName)
    val delayedQueue: RDelayedQueue[DelayJob] = client.getDelayedQueue(blockingQueue)

    val bool = delayedQueue.remove(delayJob)
    delayedQueue.destroy()
    bool
  }

  def updateJob(client: RedissonClient, delayQueueName: String, oldDelayJob: DelayJob, newDelayJob: DelayJob, delay: Long, timeUnit: TimeUnit): Boolean = {
    val blockingQueue: RBlockingQueue[DelayJob] = client.getBlockingQueue(delayQueueName)
    val delayedQueue: RDelayedQueue[DelayJob] = client.getDelayedQueue(blockingQueue)

    val bool = delayedQueue.remove(oldDelayJob)
    if (bool) delayedQueue.offer(newDelayJob, delay, timeUnit)
    delayedQueue.destroy()
    bool
  }

}
